/*
 * This file is part of ksPlatform
 * 
 * Copyright (c) 2014-2015
 * 
 * This file is dual-licensed under the AGPLv3 (http://www.gnu.org/licenses/agpl-3.0.html) 
 * 
 * If you are unsure which license is appropriate for your use, please contact the sales department
 * at 97041437@qq.com.
 */
package cn.com.ksplatform.modules.autocode.global.adapter;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.app.VelocityEngine;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.engine.jdbc.internal.FormatStyle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.velocity.VelocityConfigurer;

import cn.com.ksplatform.base.BaseController;
import cn.com.ksplatform.base.adapter.IRequestParamAdapter;
import cn.com.ksplatform.base.adapter.RuleNotFondException;
import cn.com.ksplatform.base.dao.IBaseJdbcDAO;
import cn.com.ksplatform.base.hibernate.dialect.IDialect;
import cn.com.ksplatform.base.page.PageInfoModel;
import cn.com.ksplatform.common.logger.Log;
import cn.com.ksplatform.modules.autocode.dto.Column;
import cn.com.ksplatform.modules.autocode.dto.ColumnArray;
import cn.com.ksplatform.modules.autocode.dto.Propertys;
import cn.com.ksplatform.modules.autocode.manager.model.Sence;
import cn.com.ksplatform.modules.autocode.util.SenceUtil;

/**
 * ClassName:Adapter_0_go.java <br/>
 * Date: 2015年11月18日 <br/>
 * 方法适配器
 * 
 * @author Mr.Xiao
 * @version 1.0
 */
@Component
public class Adapter_1_page implements IMethodAdapter {
	@Autowired
	@Qualifier("baseJdbcDao")
	private IBaseJdbcDAO jdbcDao;
	@Autowired
	@Qualifier("dialects.mysql")
	private IDialect mysqlDialect;
	@Autowired
	@Qualifier("dialects.oracle")
	private IDialect oracleDialect;
	@Autowired
	@Qualifier("paramAdapters.sqlRequestParamAdapter")
	private IRequestParamAdapter requestParamAdapter;
	
	@Override
	public void doAdapter(VelocityConfigurer config, 
			Sence senceModel, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String tb = request.getParameter("tb");
		ColumnArray columns = null;
		Propertys pts = SenceUtil.getPropertys(senceModel);
		String tableName = null;
		if(StringUtils.hasText(tb)){
			if(tb.equals("main")){
				columns = SenceUtil.getColumns(senceModel,"MainTable.xml");
				tableName = pts.getPropertys().get("mainTable").toString();
			}else if(tb.equals("children")){
				String sb = request.getParameter("tbName");
				columns = SenceUtil.getColumns(senceModel,"children_"+sb+".xml");
				tableName = pts.getPropertys().get("childrenTable_"+sb).toString();
			}else{
				throw new Exception("tb只能为 main或者 children");
			}
		}
		
		Map<String, List<Column>> mcls = SenceUtil.ClassifyColumns(columns);
		
		VelocityEngine ve = config.getVelocityEngine();
		Map param = new HashMap();
		//param.put("module", senceModel.getModule());
		//param.put("sence", senceModel);
		param.put("table",tableName);
		
		param.putAll(mcls);
		
		String sql = VelocityEngineUtils.mergeTemplateIntoString(ve,"cn/com/ksplatform/modules/autocode/template/sql/base/select-page.vm","UTF-8",param);
		sql = FormatStyle.BASIC.getFormatter().format(sql);
		
		
		PageInfoModel pim = new PageInfoModel();
		BaseController.class.newInstance().initPage(pim, request);
		
		try {
			Map m = requestParamAdapter.doAdapter(request,null);
			String whereSql = m.get("query").toString();
			if(StringUtils.hasText(whereSql)){
				sql += (" where "+whereSql);
			}
			Object[] params = ((List)m.get("params")).toArray();
			pim = jdbcDao.queryPage(mysqlDialect,sql,pim,params);
		} catch (RuleNotFondException e) {
			pim = jdbcDao.queryPage(mysqlDialect,sql,pim);
		}
		
		Log.info(sql);
		
		ObjectMapper mapper = new ObjectMapper();
		String pageJson = mapper.writeValueAsString(pim);
		response.setContentType("application/json");
		response.getWriter().write(pageJson);
	}
	
}
